/*===============商品基本信息部分js====================
// 分类：根据父类id获取子类列表
function renderCategoryThird(obj) {
	var index = obj.options[obj.selectedIndex].value;
	$.ajax({
		url: "/category/manage/getChildByPar",
		data:{"id":index},
		dataType: "json",
		success: function(data){
			for(var i=0; i< data.length; i++){
				html += '<option value="'+data[i].id+'">'+data[i].name+'</option>';
			}
			${"#ccate"}.html(html);
		}
	})
}

// 是否开启公益金
function gongyiIsChecked(){
	if($("#gongyiisshow1").is(':checked')){
		$('#gongyidiv').show();
	}else{
		$('#gongyidiv').hide();
	}
}

function saveProduct() {
	var displayorder = $("#displayorder").val();
	var title = $("#title").val();
	var shortTitle = $("#shortTitle").val();
	var goodscode = $("#goodscode").val();
	var specTitle = $("#specTitle").val();
	var pcate = $("#pcate").val();
	var ccate = $("#ccate").val();
	var supplierId = $("#supplierId").val();
	var unit = $("#unit").val();
	var isrecommand = $("#isrecommand").val();
	var isnew = $("#isnew").val();
	var ishot = $("#ishot").val();
	var isdiscount = $("#isdiscount").val();
	var istime = $("#istime").val();
	var ismiaosha = $("#ismiaosha").val();
	
	var islimited = $("#islimited").val();
	var selfvalue = $("#selfvalue").val();
	var timestart = $("#timestart").val();
	var timeend = $("#timeend").val();
	var thumb = $("#thumb").val();
	var thumbSquare = $("#thumbSquare").val();
	var videourl = $("#videourl").val();
	var thumbUrl = $("#thumbUrl").val();
	var marketprice = $("#marketprice").val();
	var productprice = $("#productprice").val();
	var costprice = $("#costprice").val();
	var weight = $("#weight").val();
	var total = $("#total").val();
	var maxbuy = $("#maxbuy").val();
	var usermaxbuy = $("#usermaxbuy").val();
	
	var sales = $("#sales").val();
	var viewcount = $("#viewcount").val();
	var credit = $("#credit").val();
	var status = $('input[name="status"]:checked').val();
	if(status ==2) {
		var upStartTime = $("#upStartTime").val();
		var upEndTime = $("#upEndTime").val();
	}
	var isgongyi = $('input[name="isgongyi"]:checked').val();
	if (isgongyi == 1) {
		var gongyiprice = $("#gongyiprice").val();
	}
	var showsupply = $('input[name="showsupply"]:checked').val();
	var uncancelable = $('input[name="uncancelable"]:checked').val();
	
	
	$.ajax({
		url :'',
	})
	
}



===============商品基本信息部分js====================

===========ueditor js部分，商品详情================
var ueditoroption = {
	'autoClearinitialContent': false,
	'toolbars': [['fullscreen', 'source', 'preview', '|', 'bold', 'italic', 'underline', 'strikethrough', 'forecolor', 'backcolor', '|', 'justifyleft', 'justifycenter', 'justifyright', '|', 'insertorderedlist', 'insertunorderedlist', 'blockquote', 'emotion', 'link', 'removeformat', '|', 'rowspacingtop', 'rowspacingbottom', 'lineheight', 'indent', 'paragraph', 'fontsize', '|', 'inserttable', 'deletetable', 'insertparagraphbeforetable', 'insertrow', 'deleterow', 'insertcol', 'deletecol', 'mergecells', 'mergeright', 'mergedown', 'splittocells', 'splittorows', 'splittocols', '|', 'anchor', 'map', 'print', 'drafts']],
	'elementPathEnabled': false,
	'initialFrameHeight': 200,
	'focus': false,
	'maximumWords': 9999999999999
};
var opts = {
	type: 'image',
	direct: false,
	multiple: true,
	tabs: {
		'upload': 'active',
		'browser': '',
		'crawler': ''
	},
	path: '',
	dest_dir: '',
	global: false,
	thumb: false,
	width: 0,
	fileSizeLimit: 5120000
};
UE.registerUI('myinsertimage',
function(editor, uiName) {
	editor.registerCommand(uiName, {
		execCommand: function() {
			require(['fileUploader'],
			function(uploader) {
				uploader.show(function(imgs) {
					if (imgs.length == 0) {
						return;
					} else if (imgs.length == 1) {
						editor.execCommand('insertimage', {
							'src': imgs[0]['url'],
							'_src': imgs[0]['attachment'],
							'width': '100%',
							'alt': imgs[0].filename
						});
					} else {
						var imglist = [];
						for (i in imgs) {
							imglist.push({
								'src': imgs[i]['url'],
								'_src': imgs[i]['attachment'],
								'width': '100%',
								'alt': imgs[i].filename
							});
						}
						editor.execCommand('insertimage', imglist);
					}
				},
				opts);
			});
		}
	});
	var btn = new UE.ui.Button({
		name: '插入图片',
		title: '插入图片',
		cssRules: 'background-position: -726px -77px',
		onclick: function() {
			editor.execCommand(uiName);
		}
	});
	editor.addListener('selectionchange',
	function() {
		var state = editor.queryCommandState(uiName);
		if (state == -1) {
			btn.setDisabled(true);
			btn.setChecked(false);
		} else {
			btn.setDisabled(false);
			btn.setChecked(state);
		}
	});
	return btn;
},
19);

UE.registerUI('myinsertvideo',
function(editor, uiName) {
	editor.registerCommand(uiName, {
		execCommand: function() {
			require(['fileUploader'],
			function(uploader) {
				uploader.show(function(video) {
					if (!video) {
						return;
					} else {
						var videoType = video.isRemote ? 'iframe': 'video';
						editor.execCommand('insertvideo', {
							'url': video.url,
							'width': 300,
							'height': 200
						},
						videoType);
					}
				},
				{
					fileSizeLimit: 5120000,
					type: 'video',
					allowUploadVideo: true
				});
			});
		}
	});
	var btn = new UE.ui.Button({
		name: '插入视频',
		title: '插入视频',
		cssRules: 'background-position: -320px -20px',
		onclick: function() {
			editor.execCommand(uiName);
		}
	});
	editor.addListener('selectionchange',
	function() {
		var state = editor.queryCommandState(uiName);
		if (state == -1) {
			btn.setDisabled(true);
			btn.setChecked(false);
		} else {
			btn.setDisabled(false);
			btn.setChecked(state);
		}
	});
	return btn;
},
20);


$(function() {
    var ue = UE.getEditor('content', ueditoroption);
    $('#content').data('editor', ue);
    $('#content').parents('form').submit(function() {
        if (ue.queryCommandState('source')) {
            ue.execCommand('source');
        }
    });
});
===========ueditor js部分，商品详情================
	


$(function(){
	$("#is_fx_commission").click(
		var obj = $(this);
		if (obj.get(0).checked) {
			document
					.getElementById("superiorcommission").disabled = false;
			document
					.getElementById("headcommission").disabled = false;
		} else {
			document
					.getElementById("superiorcommission").disabled = true;
			document
					.getElementById("headcommission").disabled = true;
		}
	});
})	


function show_type(flag) {
	if (flag == 0) {
		document.getElementById("sendprice").disabled = true;
		document.getElementById("dispatchid").disabled = true;

	} else if (flag == 1) {
		document.getElementById("dispatchid").disabled = true;
		document.getElementById("sendprice").disabled = false;
	} else if (flag == 2) {
		document.getElementById("sendprice").disabled = true;
		document.getElementById("dispatchid").disabled = false;
	}
}

function setCol(cls){
	$("."+cls).val( $("."+cls+"_all").val());
}
function showItem(obj){
	var show = $(obj).get(0).checked?"1":"0"; 
	$(obj).next().val(show);
}
function nofind(){
	var img=event.srcElement;
	img.src="/public/resource/image/module-nopic-small.jpg";
	img.onerror=null; 
}


function calc(){
		var spec = document.getElementById("second_spec");
		 if(spec.checked){
		  optionchanged = false;
				 var specs = [];
			       if($('.spec_item').length<=0){
			            $("#options").html('');
			            return;
			        }
				$(".spec_item").each(function(i){ 
					var _this = $(this);
			// alert(_this.find(".spec_title").val());
					var spec = {
						id: _this.find(".spec_id").val(),
						title: _this.find(".spec_title").val(),
						virtual:""
					};
				 specs.push(spec);
				});
				
				 var len = specs.length;
				 
				var newlen = 1; 
				var h = new Array(len); 
		 
				   for(var m=0;m<len;m++){
						 h[m]={title:specs[m].title,virtual: specs[m].virtual, html: "",id: specs[m].id};	
						 }
				 
				var   hh = '<input name="kw" type="hidden"  value="1"/>';
					
				for(var i=0;i<len;i++){
					var html = '<table class="table table-bordered table-condensed"><thead><tr class="active">';
					html+="<th style='width:80px;'></th>";
					html += '<th class="info" style="width:130px;"><div class=""><div style="padding-bottom:10px;text-align:center;font-size:16px;">库存</div><div class="input-group"><input type="text" class="form-control option_stock_all"VALUE=""/><span class="input-group-addon"><a href="javascript:;" class="fa fa-hand-o-down" title="批量设置" onclick="setCol(\'option_stock\');"></a></span></div></div></th>';
					html += '<th class="success" style="width:150px;"><div class=""><div style="padding-bottom:10px;text-align:center;font-size:16px;">销售价格</div><div class="input-group"><input type="text" class="form-control option_marketprice_all"VALUE=""/><span class="input-group-addon"><a href="javascript:;" class="fa fa-hand-o-down" title="批量设置" onclick="setCol(\'option_marketprice\');"></a></span></div></div></th>';
					html+='<th class="warning" style="width:150px;"><div class=""><div style="padding-bottom:10px;text-align:center;font-size:16px;">市场价格</div><div class="input-group"><input type="text" class="form-control option_productprice_all"VALUE=""/><span class="input-group-addon"><a href="javascript:;" class="fa fa-hand-o-down" title="批量设置" onclick="setCol(\'option_productprice\');"></a></span></div></div></th>';
					html+='<th class="info" style="width:150px;"><div class=""><div style="padding-bottom:10px;text-align:center;font-size:16px;">重量（克）</div><div class="input-group"><input type="text" class="form-control option_weight_all"VALUE=""/><span class="input-group-addon"><a href="javascript:;" class="fa fa-hand-o-down" title="批量设置" onclick="setCol(\'option_weight\');"></a></span></div></div></th>';
					html+='<th class="info" style="width:150px;"><div class=""><div style="padding-bottom:10px;text-align:center;font-size:16px;">门店佣金（元）</div><div class="input-group"><input type="text" class="form-control option_headcommission_all"VALUE=""/><span class="input-group-addon"><a href="javascript:;" class="fa fa-hand-o-down" title="批量设置" onclick="setCol(\'option_headcommission\');"></a></span></div></div></th>';
					html+='<th class="info" style="width:150px;"><div class=""><div style="padding-bottom:10px;text-align:center;font-size:16px;">门店推荐人佣金（元）</div><div class="input-group"><input type="text" class="form-control option_superiorcommission_all"VALUE=""/><span class="input-group-addon"><a href="javascript:;" class="fa fa-hand-o-down" title="批量设置" onclick="setCol(\'option_superiorcommission\');"></a></span></div></div></th>';
					html+='</tr></thead>';
					hh+="<tr>";
					var ids = [];
					var titles = [];    
			        var virtuals = [];
					 
					 ids =ids.join('_');
					 
				 	titles= titles.join('+');
				 
					var val ={ id : "",title:titles, stock : "",productprice : "",marketprice : "",weight:"",superiorcommission :"",headcommission :"",headtype:"",superiortype:"",virtual:virtuals };
					if( $(".option_id_" + ids).length>0){
						val ={
							id : $(".option_id_" + ids+":eq(0)").val(),
							title: titles,
							stock : $(".option_stock_" + ids+":eq(0)").val(),
							productprice : $(".option_productprice_" + ids+":eq(0)").val(),
							marketprice : $(".option_marketprice_" + ids +":eq(0)").val(),
							weight : $(".option_weight_" + ids+":eq(0)").val(),
							superiorcommission : $(".option_superiorcommission_" + ids+":eq(0)").val(),
							headcommission : $(".option_headcommission_" + ids+":eq(0)").val(),
							headtype : $(".option_headtype_" + ids+":eq(0)").val(),
							superiortype : $(".option_superiortype_" + ids+":eq(0)").val(),
							virtual : virtuals
						}
					}
					hh+="<td style='width:80px;'>" + specs[i].title + "</td>";
					hh += '<td class="info">'
					hh += '<input name="option_stock_' +  specs[i].id +'[]"type="text" class="form-control option_stock option_stock_' + specs[i].id  +'" value="' +(val.stock=='undefined'?'':val.stock )+'"/></td>';
					hh += '<input name="option_id_' + specs[i].id +'[]"type="hidden" class="form-control option_id option_id_' + specs[i].id  +'" value="' +(val.id=='undefined'?'':val.id )+'"/>';
					hh += '<input name="option_ids[]"type="hidden" class="form-control option_ids option_ids_' + specs[i].id  +'" value="' + specs[i].id  +'"/>';
					hh += '<input name="option_title_' + specs[i].id  +'[]"type="hidden" class="form-control option_title option_title_' + specs[i].id  +'" value="' +(val.title=='undefined'?'':specs[i].title  )+'"/></td>';
			        hh += '<input name="option_virtual_' + specs[i].id  +'[]"type="hidden" class="form-control option_title option_title_' + specs[i].id  +'" value="' +(val.virtual=='undefined'?'':val.virtual )+'"/></td>';
					hh += '</td>';
					hh += '<td class="success"><input name="option_marketprice_' + specs[i].id +'[]" type="text" class="form-control option_marketprice option_marketprice_' + specs[i].id  +'" value="' +(val.marketprice=='undefined'?'':val.marketprice )+'"/></td>';
					hh += '<td class="warning"><input name="option_productprice_' + specs[i].id +'[]" type="text" class="form-control option_productprice option_productprice_' + specs[i].id  +'" " value="' +(val.productprice=='undefined'?'':val.productprice )+'"/></td>';
					hh += '<td class="info"><input name="option_weight_' + specs[i].id  +'[]" type="text" class="form-control option_weight option_weight_' + specs[i].id  +'" " value="' +(val.weight=='undefined'?'':val.weight )+'"/></td>';
					// hh += '<td class="info"><input
					// name="option_headcommission_' + specs[i].id +'[]"
					// type="text" class="form-control option_headcommission
					// option_headcommission_' + specs[i].id +'" " value="'
					// +(val.headcommission=='undefined'?'':val.headcommission
					// )+'"/><span class="input-group-addon"><a
					// href="javascript:;" class="fa fa-hand-o-down"
					// title="批量设置"
					// onclick="setCol(\'option_superiorcommission\');"></a></span></td>';
					hh+='<td class="info" style="width:150px;"><div class=""><div class="input-group"><input name="option_headcommission_' + specs[i].id  +'[]" type="text" class="form-control option_headcommission option_headcommission_' + specs[i].id  +'" " value="' +(val.headcommission=='undefined'?'':val.headcommission )+'"/><span class="input-group-addon" style="padding:0px;"><select  name="option_headtype_' + specs[i].id  +'[]" type="text" class="option_headtype option_headtype_' + specs[i].id  +'"  style="border-style:solid; border-color:#FFF"  ><option value="0"  >元</option><option value="1"  >%</option></select></span></div></div></td>';
					hh+='<td class="info" style="width:150px;"><div class=""><div class="input-group"><input name="option_superiorcommission_' + specs[i].id  +'[]" type="text" class="form-control option_superiorcommission option_superiorcommission_' + specs[i].id  +'" " value="' +(val.superiorcommission=='undefined'?'':val.superiorcommission )+'"/><span class="input-group-addon" style="padding:0px;"><select  name="option_superiortype_' + specs[i].id  +'[]" type="text" class="option_superiortype option_superiortype_' + specs[i].id  +'"  style="border-style:solid; border-color:#FFF"  ><option value="0"  >元</option><option value="1"  >%</option></select></span></div></div></td>';
				    hh += "</tr>";
				}
				html+=hh;
				html+="</table>";
				$("#options").html(html);
		 }
		 
  else{
			 
			 optionchanged = false;
				var html = '<table class="table table-bordered table-condensed"><thead><tr class="active">';
				var specs = [];
			       if($('.spec_item').length<=0){
			            $("#options").html('');
			            return;
			        }
				$(".spec_item").each(function(i){ 
					var _this = $(this);
			 
					var spec = {
						id: _this.find(".spec_id").val(),
						title: _this.find(".spec_title").val()
					};
				
					var items = [];
					_this.find(".spec_item_item").each(function(){
						var __this = $(this);
						var item = {
							id: __this.find(".spec_item_id").val(),
							title: __this.find(".spec_item_title").val(),
			                virtual: __this.find(".spec_item_virtual").val(),
							show:__this.find(".spec_item_show").get(0).checked?"1":"0"
						}
						items.push(item);
					});
					spec.items = items;
					specs.push(spec);
				});
				
				
				
				specs.sort(function(x,y){
					if (x.items.length > y.items.length){
						return 1;
					}
					if (x.items.length < y.items.length) {
						return -1;
					}
				});
				 
				var len = specs.length;
				var newlen = 1; 
				var h = new Array(len); 
				var rowspans = new Array(len); 
				for(var i=0;i<len;i++){
					html+="<th style='width:80px;'>" + specs[i].title + "</th>";
					var itemlen = specs[i].items.length;
					if(itemlen<=0) { itemlen = 1 };
					newlen*=itemlen;
					h[i] = new Array(newlen);
					for(var j=0;j<newlen;j++){
						h[i][j] = new Array();
					}
					var l = specs[i].items.length;
					rowspans[i] = 1;
					for(j=i+1;j<len;j++){
						rowspans[i]*= specs[j].items.length;
					}
				}

				html += '<th class="info" style="width:130px;"><div class=""><div style="padding-bottom:10px;text-align:center;font-size:16px;">库存</div><div class="input-group"><input type="text" class="form-control option_stock_all"VALUE=""/><span class="input-group-addon"><a href="javascript:;" class="fa fa-hand-o-down" title="批量设置" onclick="setCol(\'option_stock\');"></a></span></div></div></th>';
				html += '<th class="success" style="width:150px;"><div class=""><div style="padding-bottom:10px;text-align:center;font-size:16px;">销售价格</div><div class="input-group"><input type="text" class="form-control option_marketprice_all"VALUE=""/><span class="input-group-addon"><a href="javascript:;" class="fa fa-hand-o-down" title="批量设置" onclick="setCol(\'option_marketprice\');"></a></span></div></div></th>';
				html+='<th class="warning" style="width:150px;"><div class=""><div style="padding-bottom:10px;text-align:center;font-size:16px;">市场价格</div><div class="input-group"><input type="text" class="form-control option_productprice_all"VALUE=""/><span class="input-group-addon"><a href="javascript:;" class="fa fa-hand-o-down" title="批量设置" onclick="setCol(\'option_productprice\');"></a></span></div></div></th>';
				html+='<th class="info" style="width:150px;"><div class=""><div style="padding-bottom:10px;text-align:center;font-size:16px;">重量（克）</div><div class="input-group"><input type="text" class="form-control option_weight_all"VALUE=""/><span class="input-group-addon"><a href="javascript:;" class="fa fa-hand-o-down" title="批量设置" onclick="setCol(\'option_weight\');"></a></span></div></div></th>';
				html+='<th class="info" style="width:150px;"><div class=""><div style="padding-bottom:10px;text-align:center;font-size:16px;">门店佣金（元）</div><div class="input-group"><input type="text" class="form-control option_headcommission_all"VALUE=""/><span class="input-group-addon"><a href="javascript:;" class="fa fa-hand-o-down" title="批量设置" onclick="setCol(\'option_headcommission\');"></a></span></div></div></th>';
				html+='<th class="info" style="width:150px;"><div class=""><div style="padding-bottom:10px;text-align:center;font-size:16px;">门店推荐人佣金（元）</div><div class="input-group"><input type="text" class="form-control option_superiorcommission_all"VALUE=""/><span class="input-group-addon"><a href="javascript:;" class="fa fa-hand-o-down" title="批量设置" onclick="setCol(\'option_superiorcommission\');"></a></span></div></div></th>';
				html+='</tr></thead>';
				 
					  
					 for(var m=0;m<len;m++){
							var k = 0,kid = 0,n=0;
							for(var j=0;j<newlen;j++){
								var rowspan = rowspans[m]; 
								 
								if( j % rowspan==0){
									h[m][j]={title: specs[m].items[kid].title, virtual: specs[m].items[kid].virtual,html: "<td rowspan='" +rowspan + "'>"+ specs[m].items[kid].title+"</td>\r\n",id: specs[m].items[kid].id};
								}
								else{
									h[m][j]={title:specs[m].items[kid].title,virtual: specs[m].items[kid].virtual, html: "",id: specs[m].items[kid].id};	
								}
								n++;
								if(n==rowspan){
								kid++; if(kid>specs[m].items.length-1) { kid=0; }
								n=0;
								}
							}
						}
				 
					 var   hh = '<input name="kw" type="hidden"  value="0"/>';
				for(var i=0;i<newlen;i++){
				 
					hh+="<tr>";
					var ids = [];
					var titles = [];    
			        var virtuals = [];
					for(var j=0;j<len;j++){
						hh+=h[j][i].html; 
						ids.push( h[j][i].id);
						titles.push( h[j][i].title);
			            virtuals.push( h[j][i].virtual);
					}
					ids =ids.join('_');
					titles= titles.join('+');
				 
					var val ={ id : "",title:titles, stock : "",productprice : "",marketprice : "",weight:"",superiorcommission :"",headcommission :"",virtual:virtuals };
					if( $(".option_id_" + ids).length>0){
						val ={
							id : $(".option_id_" + ids+":eq(0)").val(),
							title: titles,
							stock : $(".option_stock_" + ids+":eq(0)").val(),
							productprice : $(".option_productprice_" + ids+":eq(0)").val(),
							marketprice : $(".option_marketprice_" + ids +":eq(0)").val(),
							weight : $(".option_weight_" + ids+":eq(0)").val(),
							superiorcommission : $(".option_superiorcommission_" + ids+":eq(0)").val(),
							headcommission : $(".option_headcommission_" + ids+":eq(0)").val(),
							headtype : $(".option_headtype_" + ids+":eq(0)").val(),
							superiortype : $(".option_superiortype_" + ids+":eq(0)").val(),
			                virtual : virtuals
						}
					}
					hh += '<td class="info">'
					hh += '<input name="option_stock_' + ids +'[]"type="text" class="form-control option_stock option_stock_' + ids +'" value="' +(val.stock=='undefined'?'':val.stock )+'"/></td>';
					hh += '<input name="option_id_' + ids+'[]"type="hidden" class="form-control option_id option_id_' + ids +'" value="' +(val.id=='undefined'?'':val.id )+'"/>';
					hh += '<input name="option_ids[]"type="hidden" class="form-control option_ids option_ids_' + ids +'" value="' + ids +'"/>';
					hh += '<input name="option_title_' + ids +'[]"type="hidden" class="form-control option_title option_title_' + ids +'" value="' +(val.title=='undefined'?'':val.title )+'"/></td>';
			        hh += '<input name="option_virtual_' + ids +'[]"type="hidden" class="form-control option_title option_title_' + ids +'" value="' +(val.virtual=='undefined'?'':val.virtual )+'"/></td>';
					hh += '</td>';
					hh += '<td class="success"><input name="option_marketprice_' + ids+'[]" type="text" class="form-control option_marketprice option_marketprice_' + ids +'" value="' +(val.marketprice=='undefined'?'':val.marketprice )+'"/></td>';
					hh += '<td class="warning"><input name="option_productprice_' + ids+'[]" type="text" class="form-control option_productprice option_productprice_' + ids +'" " value="' +(val.productprice=='undefined'?'':val.productprice )+'"/></td>';
					hh += '<td class="info"><input name="option_weight_' + ids +'[]" type="text" class="form-control option_weight option_weight_' + ids +'" " value="' +(val.weight=='undefined'?'':val.weight )+'"/></td>';
					// hh += '<td class="info"><input
					// name="option_headcommission_' + ids +'[]" type="text"
					// class="form-control option_headcommission
					// option_headcommission_' + ids +'" " value="'
					// +(val.headcommission=='undefined'?'':val.headcommission
					// )+'"/></td>';
				// hh += '<td class="info"><input
				// name="option_superiorcommission_' + ids +'[]" type="text"
				// class="form-control option_superiorcommission
				// option_superiorcommission_' + ids +'" " value="'
				// +(val.superiorcommission=='undefined'?'':val.superiorcommission
				// )+'"/></td>';
					hh+='<td class="info" style="width:150px;"><div class=""><div class="input-group"><input name="option_headcommission_' + ids  +'[]" type="text" class="form-control option_headcommission option_headcommission_' + ids  +'" " value="' +(val.headcommission=='undefined'?'':val.headcommission )+'"/><span class="input-group-addon" style="padding:0px;"><select  name="option_headtype_' + ids  +'[]" type="text" class="option_headtype option_headtype_' + ids  +'"  style="border-style:solid; border-color:#FFF"  ><option value="0"  >元</option><option value="1"  >%</option></select></span></div></div></td>';
					hh+='<td class="info" style="width:150px;"><div class=""><div class="input-group"><input name="option_superiorcommission_' + ids  +'[]" type="text" class="form-control option_superiorcommission option_superiorcommission_' + ids  +'" " value="' +(val.superiorcommission=='undefined'?'':val.superiorcommission )+'"/><span class="input-group-addon" style="padding:0px;"><select  name="option_superiortype_' + ids +'[]" type="text" class="option_superiortype option_superiortype_' + ids +'"  style="border-style:solid; border-color:#FFF"  ><option value="0"  >元</option><option value="1"  >%</option></select></span></div></div></td>';
				    hh += "</tr>";
				}
				html+=hh;
				html+="</table>";
				$("#options").html(html);
		 }
}

function removeSpec(specid) {
	if (confirm('确认要删除此规格?')) {
		$("#spec_" + specid).remove();
		optionchanged = true;
	}
}
function addSpecItem(specid) {
	$("#add-specitem-" + specid)
			.html("正在处理...").attr("disabled",
					"true");
	var url = "/admin/goods/tpl_specitem.html";
	$
			.ajax({
				type : "get",
				"url" : url,
				data : {
					specid : specid
				},
				success : function(data) {
					$("#add-specitem-" + specid)
							.html(
									'<i class="fa fa-plus"></i> 添加规格项')
							.removeAttr(
									"disabled");
					$('#spec_item_' + specid)
							.append(data);
					var len = $("#spec_"
							+ specid
							+ " .spec_item_title").length - 1;
					$(
							"#spec_"
									+ specid
									+ " .spec_item_title:eq("
									+ len + ")")
							.focus();
					optionchanged = true;

				}
			});
}

$(function() {

	$("#second_spec").click(
					function() {
						var obj = $(this);
						var aDiv = document
								.getElementsByName('listspec');
						var aDivdel = document
								.getElementsByName('listspecdel');
						if (obj.get(0).checked) {
							$("#listspecdel")
									.hide();
							for (var i = 0; i < aDiv.length; i++) {
								aDiv[i].style.display = "none";
								aDivdel[i].style.display = "";
							}
						} else {

							for (var i = 0; i < aDiv.length; i++) {
								aDiv[i].style.display = "";
								aDivdel[i].style.display = "none";
							}
						}
					});
})


								
								
$().ready(function() {
    $('.cityall').click(function() {
        var checked = $(this).get(0).checked;
        var citys = $(this).parent().parent().find('.city');
        citys.each(function() {
            $(this).get(0).checked = checked;
        });
        var count = 0;
        if (checked) {
            count = $(this).parent().parent().find('.city:checked').length;
        }
        if (count > 0) {
            $(this).next().html("(" + count + ")");
        } else {
            $(this).next().html("");
        }
    });

    $('.city').click(function() {
        var checked = $(this).get(0).checked;
        var cityall = $(this).parent().parent().parent().parent().find('.cityall');

        if (checked) {
            cityall.get(0).checked = true;
        }
        var count = cityall.parent().parent().find('.city:checked').length;
        if (count > 0) {
            cityall.next().html("(" + count + ")");
        } else {
            cityall.next().html("");
        }
    });

    function clearSelects() {
        $('.city').attr('checked', false).removeAttr('disabled');
        $('.cityall').attr('checked', false).removeAttr('disabled');
        $('.citycount').html('');
    }

    function editArea(btn) {
        current = $(btn).attr('random');
        clearSelects();
        var old_citys = $(btn).prev().val().split(';');

        $('.city').each(function() {
            var parentcheck = false;
            for (var i in old_citys) {
                if (old_citys[i] == $(this).attr('city')) {
                    parentcheck = true;
                    $(this).get(0).checked = true;
                    break;
                }
            }
            if (parentcheck) {
                $(this).parent().parent().parent().parent().find('.cityall').get(0).checked = true;
            }
        });

        $("#modal-areas").modal();
        var citystrs = '';
        $('#btnSubmitArea').unbind('click').click(function() {
            $('.city:checked').each(function() {
                citystrs += $(this).attr('city') + ";";
            });
            $('.' + current + ' .cityshtml').html(citystrs);
            $('.' + current + ' .citys').val(citystrs);
        }) var currents = getCurrents(current);
        currents = currents.split(';');
        var citys = "";
        $('.city').each(function() {
            var parentdisabled = false;
            for (var i in currents) {
                if (currents[i] != '' && currents[i] == $(this).attr('city')) {
                    $(this).attr('disabled', true);
                    $(this).parent().parent().parent().parent().find('.cityall').attr('disabled', true);
                }
            }

        });
    }
    
    function selectAreas(){
        clearSelects();
        var old_citys = $('#areas').html().split(';');
        $('.city').each(function(){
            var parentcheck = false;
            for(var i in old_citys){
                if(old_citys[i]==$(this).attr('city')){
                    parentcheck = true;
                    $(this).get(0).checked = true;
                    break;
                }
            }
            if(parentcheck){
                $(this).parent().parent().parent().parent().find('.cityall').get(0).checked=  true;
            }
        });
        
        $("#modal-areas").modal();
        var citystrs = '';
        $('#btnSubmitArea').unbind('click').click(function(){
                   $('.city:checked').each(function(){              
                       citystrs+= $(this).attr('city') +";";
                   }); 
                   $('#areas').html(citystrs);
                   $("#selectedareas").val(citystrs);
        })
    }
    
    
    function addSpec() {
        second_spec = 0;
        var spec = document.getElementById("second_spec");
        if (spec.checked) {

            second_spec = 1;
        }

        var len = $(".spec_item").length;

        $("#add-spec").html("正在处理...").attr("disabled", "true").toggleClass("btn-primary");
        var url = "/admin/goods/tpl_spec.html";
        $.ajax({
            type: "get",
            data: {
                'second_spec': second_spec
            },
            "url": url,
            success: function(data) {

                $("#add-spec").html('<i class="fa fa-plus"></i> 添加规格').removeAttr("disabled").toggleClass("btn-primary");;
                $('#specs').append(data);
                var len = $(".add-specitem").length - 1;
                $(".add-specitem:eq(" + len + ")").focus();

                optionchanged = true;
            }
        });
    }
    
    var optionchanged = false;
    $(function() {
        $('#specs').sortable({
            stop: function() {
                optionchanged = true;
            }
        });
        $('.spec_item_items').sortable({
            handle: '.fa-arrows',
            stop: function() {
                optionchanged = true;
            }
        });
        $("#hasoption").click(function() {
            var obj = $(this);
            if (obj.get(0).checked) {
                $("#tboption").show();
                $("#second_speccid").show();
            } else {
                $("#tboption").hide();
                $("#second_speccid").hide();
            }
        });
    })
    
    function addtemp(){
        var id = $('#modal-module-chooestemp').data("temp");
        var temp_id = $('#modal-module-chooestemp').find("select").val();
        var temp_name = $('#modal-module-chooestemp option[value='+temp_id+']').text();
        // alert(temp_id+":"+temp_name);
        $("#temp_name_"+id).val(temp_name);
        $("#temp_id_"+id).val(temp_id);
        $('#modal-module-chooestemp .close').click();
        optionchanged = true;
    }

    function removeSpecItem(obj){
    	$(obj).parent().parent().parent().remove();
    }

});


function selectAreas(){
    clearSelects();
    var old_citys = $('#areas').html().split(';');
    $('.city').each(function(){
        var parentcheck = false;
        for(var i in old_citys){
            if(old_citys[i]==$(this).attr('city')){
                parentcheck = true;
                $(this).get(0).checked = true;
                break;
            }
        }
        if(parentcheck){
            $(this).parent().parent().parent().parent().find('.cityall').get(0).checked=  true;
        }
    });
    
    $("#modal-areas").modal();
    var citystrs = '';
    $('#btnSubmitArea').unbind('click').click(function(){
               $('.city:checked').each(function(){              
                   citystrs+= $(this).attr('city') +";";
               }); 
               $('#areas').html(citystrs);
               $("#selectedareas").val(citystrs);
    })

}

function clearSelects(){
     $('.city').attr('checked',false).removeAttr('disabled');
     $('.cityall').attr('checked',false).removeAttr('disabled');
     $('.citycount').html('');
}
*/
